package com.handsoninfo;

import net.sourceforge.tess4j.Word;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public interface Utils {
    int BLUE_THRESHOLD = 30;
    int BLACK_THRESHOLD = 30;
    static Boolean isBlue(BufferedImage bi, Word word) {

        if ((word.getConfidence() < 50 && !allDigits(word.getText())) || containsPunctuation(word.getText())) {
//            System.out.println(word.getConfidence() + " : " + word.getText());
            return null;
        }

        Rectangle rect = word.getBoundingBox();

        List<RGBColor> pixels = new ArrayList<>();

        for (int i = 0; i < rect.width; i += 1) {
            for (int j = 0; j < rect.height; j += 1) {
                int color = bi.getRGB(i + rect.x, j + rect.y);
                pixels.add(new RGBColor(color));
            }
        }

        RGBCounter counter = new RGBCounter(pixels);

        List<RGBColor> black = Arrays.asList(new RGBColor(0, 0, 0), new RGBColor(121, 120, 125), new RGBColor(40, 38, 43));
        List<RGBColor> blue = Arrays.asList(new RGBColor(0, 0, 255), new RGBColor(61, 120, 150), new RGBColor(61, 87, 121));

        int blackCount = counter.count(black, BLACK_THRESHOLD);

        int blueCount = counter.count(blue, BLUE_THRESHOLD);

        if (blackCount + blueCount == 0) {
            System.err.println("!!both zero!! " + word.getText());
        }

        return !(blueCount < blackCount);

    }
    static Color getTextColor(BufferedImage bi, Word word) {

        Color black = new Color(0, 0, 0);
        Color blue = new Color(0, 0, 255);

        Boolean isBlue = isBlue(bi, word);

        if (isBlue == null) return null;

        return isBlue ? blue : black;

    }

    static boolean allDigits(String text) {
        for (char c : text.toCharArray()) {
            if (!Character.isDigit(c)) return false;
        }
        return true;
    }

    static boolean containsPunctuation(String text) {
        if (Pattern.matches("\\p{P}", text)) return true;
        for (char c : text.toCharArray()) {
            if (isChinesePunctuation(c)) return true;
        }
        return false;
    }
    /**
     * 根据UnicodeBlock方法判断中文标点符号
     *
     */
    static boolean isChinesePunctuation(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS
                || ub == Character.UnicodeBlock.VERTICAL_FORMS;
    }
}
